<?php

declare(strict_types=1);

namespace App\CustHub\Service;


use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Psr\Container\ContainerInterface;
use function FriendsOfHyperf\Lock\lock;

class RestService
{

    private ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * 保存用户信息
     * @param array $data
     * @return false|void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function saveUser(array $data)
    {
        $wxUser = \Hyperf\Collection\data_get($data,'wxUser');
        $tag = \Hyperf\Collection\data_get($data,'tag');
        $ip = \Hyperf\Collection\data_get($data,'ip');
        if(empty($wxUser) || empty($tag)){
            return false;
        }

        $key = 'su_user_save_lock:'.md5(json_encode($wxUser));
        $lock = lock($key,6);
        try {
            $lock->block(4);
            // 根据参数处理具体逻辑
            $this->container->get(ChUserService::class)->saveUser($wxUser,$tag,$ip);
        }catch (LockTimeoutException $e){
            logger()->info('用户扫码登录注册失败，锁被占用'.json_encode($wxUser,JSON_UNESCAPED_UNICODE));
            return false;
        } finally {
            $lock->release();
        }
    }
}